package shayu.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import io.renren.common.to.es.SkuEsModel;
import io.renren.common.utils.R;
import jodd.util.StringUtil;
import org.apache.lucene.search.join.ScoreMode;
import org.bouncycastle.est.CACertsResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import shayu.search.config.ShopElasticSearchConfig;
import shayu.search.constant.EsConstant;
import shayu.search.feign.ProductFeignService;
import shayu.search.service.MallSearchService;
import shayu.search.vo.AttrResponseVo;
import shayu.search.vo.BrandVo;
import shayu.search.vo.SearchParm;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ProductFeignService productFeignService;

    // 去es中检索

    @Override
    public SearchParm search(SearchParm searchParm) {
        // 1. 动态构建出需要检索的DSL语句

        // 1.1 准备检索请求
        SearchRequest searchRequest = new SearchRequest();

        try {
            restHighLevelClient.search(searchRequest, ShopElasticSearchConfig.COMMON_OPTIONS);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 准备检索请求
     * #模糊匹配：过滤（按照属性，分类，品牌，价格区间，库存）排序分页高亮聚合分析
     * * @param searchParm
     *
     * @return
     */
    public SearchRequest buildSearchRequrest(SearchParm searchParm) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询，过滤(按照属性，分类，品牌，价格区间，库存)
        // 1 构建bool-query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 1.1 must- 模糊查询
        if (!StringUtil.isEmpty(searchParm.getKeyword())) {
            boolQuery.must(QueryBuilders.multiMatchQuery("skuTitle", searchParm.getKeyword()));
        }

        // 1.2 bool-filter - 按照三级分类id查
        if (searchParm.getCataloy3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", searchParm.getCataloy3Id()));
        }

        // 1.3 bool-filter - 按照品牌id查询
        if (searchParm.getBrandId() != null && searchParm.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termQuery("brandId", searchParm.getBrandId()));
        }

        // 1.4 按照所有指定的属性进行查询
        if (searchParm.getAttrs() != null && searchParm.getAttrs().size() > 0) {
            for (String attrStr : searchParm.getAttrs()) {
                BoolQueryBuilder nestedboolQuety = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String arrrId = s[0]; // 检索的属性id
                String[] attrValues = s[1].split(":"); // 这个属性的检索用的值
                nestedboolQuety.must(QueryBuilders.termQuery("attrs.attrId", arrrId));
                nestedboolQuety.must(QueryBuilders.termQuery("attrs.attrValue", attrValues));
                QueryBuilders.nestedQuery("attrs", nestedboolQuety, ScoreMode.Avg);
                boolQuery.filter(nestedboolQuety);
            }
        }

        // 1.5 bool -filter - 查询有没有库存
        if (searchParm.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", searchParm.getHasStock() == 1));
        }

        // 1.6 bool -filter - 按照价格区间查
        if (!StringUtil.isEmpty(searchParm.getSkuPrice())) {

            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");

            String[] s = searchParm.getSkuPrice().split("_");
            // 区间
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                if (searchParm.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[1]);
                }
                if (searchParm.getSkuPrice().endsWith("_")) {
                    rangeQuery.gte(s[0]);
                }
            }
        }

        // 封装
        sourceBuilder.query(boolQuery);

        // 2.1 排序，分页，高亮
        if (!StringUtil.isEmpty(searchParm.getSort())) {
            String sort = searchParm.getSort();
            String[] s = sort.split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(s[0], order);
        }

        // 2.2 分页
        sourceBuilder.from((int) ((searchParm.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE));
        sourceBuilder.size(Math.toIntExact(EsConstant.PRODUCT_PAGESIZE));

        // 2.3 高亮
        if (!StringUtil.isEmpty(searchParm.getKeyword())) {
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.preTags("</br>");
            sourceBuilder.highlighter(builder);
        }

        /**
         *  聚合分析
         */

        // 3.1 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brand_id").size(50);
        // 品牌聚合的子查询
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(50));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(50));

        sourceBuilder.aggregation(brand_agg);

        // 3.2 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogAgg").size(50);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogNameAgg")).size(50);
        sourceBuilder.aggregation(catalog_agg);

        // 3. 属性聚合 arrt_agg
        NestedAggregationBuilder arrt_agg = AggregationBuilders.nested("attt_agg", "attrs");

        // 聚合出当前所有的attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrIdAgg").size(50);
        // 聚合分析出当前attr_id对应的名字
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrNameAgg")).size(50);
        // 聚合分析出当前attr_id对应的所有可能的属性值
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attr.attrValue")).size(50);
        attr_id_agg.subAggregation(attr_id_agg);
        sourceBuilder.aggregation(attr_id_agg);

        String s = sourceBuilder.toString();
        System.out.println("构建的DSL" + s);


        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
        return searchRequest;
    }

    /**
     * 构建架构数据
     * 模糊匹配：过滤(按照属性，分析，品牌，价格区间，库存)，完成排序，分页 ，高亮，聚合分析功能
     */
    private shayu.search.vo.SearchResponse buildSearchResult(SearchResponse response, SearchParm searchParm) {
        shayu.search.vo.SearchResponse result = new shayu.search.vo.SearchResponse();

        // 1. 返回所有查询到的商品
        SearchHits hits = response.getHits();
        ArrayList<SkuEsModel> skuEsModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (!StringUtil.isEmpty(searchParm.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String title = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(title);
                }
                skuEsModels.add(skuEsModel);
            }
        }
        result.setProducts(skuEsModels);

        // 2. 当前所有商品涉及到的所有属性信息
        ArrayList<shayu.search.vo.SearchResponse.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = response.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            shayu.search.vo.SearchResponse.AttrVo attrVo = new shayu.search.vo.SearchResponse.AttrVo();
            // 2.1 得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            // 2.2 得到属性的名字
            String attr_name_agg = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            // 2.3 得到属性的所有值
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = attr_id_agg.getBuckets().stream().map(item -> item.getKeyAsString()).collect(Collectors.toList());
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attr_name_agg);
            attrVo.setAttrValue(attrValues);
        }
        result.setAttrs(attrVos);

        // 3. 当前所有商品涉及到的所有品牌信息
        ArrayList<shayu.search.vo.SearchResponse.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            shayu.search.vo.SearchResponse.BrandVo brandVo = new shayu.search.vo.SearchResponse.BrandVo();
            // 3.1 得到品牌的id
            long brandId = bucket.getKeyAsNumber().longValue();
            // 3.2 得到品牌的名字
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            // 3.3 得到品牌的图片
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

        // 4. 当前所有商品涉及到的所有分类信息
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        ArrayList<shayu.search.vo.SearchResponse.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            shayu.search.vo.SearchResponse.CatalogVo catalogVo = new shayu.search.vo.SearchResponse.CatalogVo();
            // 得到分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogd(Long.parseLong(keyAsString));

            // 得到分类名
            ParsedLongTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalog_name = catalog_name_agg.getBuckets().get(0).toString();
            catalogVo.setCatalogName(catalog_name);
            catalogVos.add(catalogVo);
        }

        result.setCatalogVos(catalogVos);

        // 5.1 分页信息-页码
        result.setPageNum(searchParm.getPageNum());
        // 5.2 分页信息-总记录数
        long total = hits.getTotalHits().value;
        result.setTotal(total);

        // 5.3 分页信息-总页码- 计算 11/2=5。。1
        int totalPages = (int) ((int) total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE : (int) total / EsConstant.PRODUCT_PAGESIZE);

        result.setTotalPages(totalPages);

        // 5.4 分页数
        ArrayList<Integer> pagenavs = new ArrayList<>();
        for (int i = 1; i < totalPages; i++) {
            pagenavs.add(i);
        }

        result.setPageNavs(pagenavs);

        // 6. 构建面包屑导航工具
        if (searchParm.getAttrs().size() > 0 && searchParm.getAttrs() != null) {
            List<shayu.search.vo.SearchResponse.NavVo> collect = searchParm.getAttrs().stream().map(attr -> {
                shayu.search.vo.SearchResponse.NavVo navVo = new shayu.search.vo.SearchResponse.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }
                // 6.1 取消了这个看看面包屑之后，我们要跳转的地方
                // 拿到所有的查询条件，去掉当前
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr, "UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                String replace = searchParm.get_queryString().replace("&attrs=", encode);
                navVo.setLink("http://127.0.0.1/list.html?" + replace);
                return navVo;
            }).collect(Collectors.toList());

            result.setNavs(collect);
        }

        // 品牌，分类
        if (searchParm.getBrandId() != null && searchParm.getBrandId().size() > 0) {
            List<shayu.search.vo.SearchResponse.NavVo> navs = result.getNavs();
            shayu.search.vo.SearchResponse.NavVo navVo = new shayu.search.vo.SearchResponse.NavVo();
            navVo.setNavName("品牌");
            R r = productFeignService.info(searchParm.getBrandId());
            if (r.getCode() == 0) {
                List<shayu.search.vo.SearchResponse.BrandVo> brand = r.getData("brand", new TypeReference<List<shayu.search.vo.SearchResponse.BrandVo>>() {
                });
                StringBuffer stringBuffer = new StringBuffer();
                String replace = null;
                for (shayu.search.vo.SearchResponse.BrandVo brandVo : brand) {
                    stringBuffer.append(brandVo.getBrandName() + ";");

                }
                navVo.setNavValue(stringBuffer.toString());
            }
            navs.add(navVo);
        }

        return result;
    }
}
